import socket


class ClinetSocket(object):

    def __init__(self):
        self.remote_ip = "192.168.153.1"
        self.remote_port = 8080
        self.local_ip = "192.168.153.1"
        self.local_port = 9999

    def run(self):
        # 创建套接字
        clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # # 设置端口立马释放
        # clientSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # # 绑定本地ip+端口
        # clientSocket.bind((self.local_ip, self.local_port))
        # 链接服务端
        clientSocket.connect((self.remote_ip, self.remote_port))
        # 发送数据
        content = input("请输入发送的数据:")
        clientSocket.send(content.encode("utf-8"))
        # 接收服务端数据
        data = clientSocket.recv(1024)
        print(data.decode("gbk"))
        clientSocket.close()


class ServerSocket(object):
    def __init__(self):
        self.local_ip = "192.168.153.1"
        self.local_port = 8080

    def run(self):
        # 创建套接字
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 绑定服务端本地ip和端口
        server_socket.bind((self.local_ip, self.local_port))
        # 监听最大限制
        server_socket.listen(5)
        while True:
            # 等待客户端链接
            # client_socket和客户端交互使用
            # client_addr_socket储存客户端信息
            client_socket, client_addr_socket = server_socket.accept()
            print(client_addr_socket)
            while True:
                # 接收客户端信息
                client_data = client_socket.recv(1024)
                # 如果对方直接调用close方法，接收的数据就是空字符串
                if client_data.decode("gbk") == "":
                    break
                print(client_data.decode("gbk"))
                # 发送信息到客户端
                client_socket.send("我接收到了".encode("utf-8"))
                # 释放客户端服务，如果还需要服务，只能再次重新连接
            client_socket.close()
        # 释放服务端服务
        server_socket.close()


if __name__ == "__main__":
    # client = ClinetSocket()
    # client.run()
    server = ServerSocket()
    server.run()
